package com.greenant.store.activity;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVRelation;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SaveCallback;
import com.avos.avoscloud.LogUtil.log;
import com.greenant.store.R;
import com.greenant.store.adapter.MyAdapter;
import com.greenant.store.bean.AntGoods;
import com.greenant.store.utils.Bimp;
import com.greenant.store.utils.FileUtils;

public class AddActivity extends Activity {
	
	private TextView tTitle;
	private ImageView iBack;
	private TextView iAdd;
	private Resources res;
	private GridView imageGrid;
	private GridAdapter adapter;
	private int itemIndex;
	private EditText descripEditText;
	private EditText priceEditText;
	private EditText stockEditText;
	private EditText unitEditText;
	
	private List<AVObject> myStores=null;
	private List<AVObject> mySections=null;
	
	public ArrayList<Integer> imageArray ;
	 @Override
	 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        res=getResources();
        
        Bimp.reset();
        //�Զ���ActionBar  
        final ActionBar actionBar = getActionBar();  
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);  
        actionBar.setCustomView(R.layout.actionbar);//�Զ���ActionBar����  
       
        iBack = (ImageView)findViewById(R.id.left_btn);
        iAdd = (TextView)findViewById(R.id.right_btn);
        tTitle = (TextView)findViewById(R.id.actionbar_title);
        descripEditText = (EditText)findViewById(R.id.editDescription);
        priceEditText = (EditText)findViewById(R.id.editPrice);
        stockEditText = (EditText)findViewById(R.id.editStock);            
        unitEditText = (EditText)findViewById(R.id.editUnit);     
                    
        tTitle.setText(res.getText(R.string.title_activity_add));
        
        iBack.setOnClickListener(new OnClickListener()
        {	
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
         	    finish();
			}
        	
        });
        iAdd.setText(res.getText(R.string.action_finish));
        iAdd.setOnClickListener(new OnClickListener()
        {	
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub	
				
				if (Bimp.max<=0)
				{
					Toast.makeText(AddActivity.this, 
							AddActivity.this.getResources().getString(
									R.string.add_photo_tip) , 
									Toast.LENGTH_SHORT).show();
				}else
				if (descripEditText.getText().toString().length()==0){
					Toast.makeText(AddActivity.this, 
							AddActivity.this.getResources().getString(
									R.string.description_tip) , 
									Toast.LENGTH_SHORT).show();
				}else 
				if (priceEditText.getText().toString().length()==0){
					Toast.makeText(AddActivity.this, 
							AddActivity.this.getResources().getString(
									R.string.price_tip) , 
									Toast.LENGTH_SHORT).show();
				}else
				if (stockEditText.getText().toString().length()==0){
					Toast.makeText(AddActivity.this, 
							AddActivity.this.getResources().getString(
									R.string.stoke_tip) , 
									Toast.LENGTH_SHORT).show();
				}
				else {
					upLoadGoods();
					finish();
				}				
			}
        });
             
        /*������Ʒ����*/
        LinearLayout descrip = (LinearLayout)findViewById(R.id.linearLayout3); 

        descrip.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
        	  descripEditText.requestFocus();
           }

         });
        avsRelationQuery();
        InitImageGrid();
	 }

	 public void InitImageGrid() {
		 	imageGrid =(GridView)findViewById(R.id.gv);
		 	imageGrid.setSelector(new ColorDrawable(Color.TRANSPARENT));
			adapter = new GridAdapter(this);
			adapter.update();
			imageGrid.setAdapter(adapter);
			
			imageGrid.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> parent, View v, int position,long id) {
					if (position == Bimp.bmp.size())
					{
						Intent intent = new Intent(AddActivity.this,
								ImageLoadActivity.class);
						intent.putExtra("ID", position);
						startActivity(intent);	
					}
					else 
					{
						/*Intent intent = new Intent(AddActivity.this,
								PhotoActivity.class);
						intent.putExtra("ID", position);
						startActivity(intent);*/
						itemIndex = position;
					}
				}
			});
	 }	
	 
	 @SuppressLint("HandlerLeak")
		public class GridAdapter extends BaseAdapter {
			private LayoutInflater inflater; // ��ͼ����
			private int selectedPosition = -1;// ѡ�е�λ��
			private boolean shape;

			public boolean isShape() {
				return shape;
			}

			public void setShape(boolean shape) {
				this.shape = shape;
			}

			public GridAdapter(Context context) {
				inflater = LayoutInflater.from(context);
			}

			public void update() {
				loading();
			}

			public int getCount() {
				return (Bimp.bmp.size() + 1);
			}

			public Object getItem(int arg0) {

				return null;
			}

			public long getItemId(int arg0) {

				return 0;
			}

			public void setSelectedPosition(int position) {
				selectedPosition = position;
			}

			public int getSelectedPosition() {
				return selectedPosition;
			}

			/**
			 * ListView Item����
			 */
			public View getView(int position, View convertView, ViewGroup parent) {
				
				ViewHolder holder = null;
				if (convertView == null) {

					convertView = inflater.inflate(R.layout.item_add_grid,
							parent, false);
					holder = new ViewHolder();
					holder.image = (ImageView) convertView
							.findViewById(R.id.item_grid_image);
					holder.del = (ImageView) convertView
							.findViewById(R.id.item_grid_del);					
					convertView.setTag(holder);
				} else {
					holder = (ViewHolder) convertView.getTag();
				}
					
				holder.del.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View v) {

						//Toast.makeText(AddActivity.this, "delete", Toast.LENGTH_LONG).show();
						if (Bimp.drr.size() == 1) {
							Bimp.bmp.clear();
							Bimp.drr.clear();
							Bimp.max = 0;
							FileUtils.deleteDir();
						} else {
							String path = Bimp.drr.get(itemIndex);
							Bimp.bmp.remove(itemIndex);
							Bimp.drr.remove(itemIndex);
							Log.d("del","Bimp.max=%d"+Bimp.max);
							if (Bimp.max>0)
								Bimp.max--;
							FileUtils.delFile(path);
						}
						adapter.notifyDataSetChanged();
					}
				});
				 
				if (position == Bimp.bmp.size()) {
					holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.ic_kdwd_add_img_down));
					
					if (position == MyAdapter.maxGridCount) {
						holder.image.setVisibility(View.GONE);						
					}
					holder.del.setVisibility(View.GONE);
				} else {
					holder.del.setVisibility(View.VISIBLE);
					holder.image.setImageBitmap(Bimp.bmp.get(position));
					holder.del.setImageResource(R.drawable.ic_kdwd_goods_img_pre_del);
				}

/*				ViewGroup.LayoutParams params = imageGrid.getLayoutParams();   
				params.height =140;
				imageGrid.setLayoutParams(params);
				((MarginLayoutParams) params).setMargins(10, 10, 10, 10);*/
						
				return convertView;
			}

			public class ViewHolder {
				public ImageView image;
				public ImageView del;
			}

			Handler handler = new Handler() {
				public void handleMessage(Message msg) {
					switch (msg.what) {
					case 1:
						adapter.notifyDataSetChanged();
						break;
					}
					super.handleMessage(msg);
				}
			};

			public void loading() {
				new Thread(new Runnable() {
					public void run() {
						while (true) {	
							Log.d("sgz","Bimp.max=%d"+Bimp.max);
							if (Bimp.max == Bimp.drr.size()) {
								Message message = new Message();
								message.what = 1;
								handler.sendMessage(message);
								break;
							} else {
								try {
									String path = Bimp.drr.get(Bimp.max);
									System.out.println(path);
									Bitmap bm = Bimp.revitionImageSize(path);
									Bimp.bmp.add(bm);
									String newStr = path.substring(
											path.lastIndexOf("/") + 1,
											path.lastIndexOf("."));
									FileUtils.saveBitmap(bm, "" + newStr);
									Bimp.max+=1;
									Message message = new Message();
									message.what = 1;
									handler.sendMessage(message);
								} catch (IOException e) {

									e.printStackTrace();
								}
							}
						}
					}
				}).start();
			}
		}

		public String getString(String s) {
			String path = null;
			if (s == null)
				return "";
			for (int i = s.length() - 1; i > 0; i++) {
				s.charAt(i);
			}
			return path;
		}

		protected void onRestart() {
			adapter.update();
			super.onRestart();
		}

		private void upLoadGoods()
		{
			int tmpInt = 0;
			float price =0;
			final AntGoods avGoods=new AntGoods();		
			
			if (Bimp.max<=0)
			{
				return;
			}
			
			if (mySections != null&&mySections.size()>0){
				AVRelation<AVObject>relation=avGoods.getRelation("uptowns");
				for (AVObject section : mySections) {		            	
					relation.add(section);
		        }	
			}
			String path = Bimp.drr.get(0);
			//log.d("av","path="+path);
			
			avGoods.setUserId(AVUser.getCurrentUser().getObjectId());
			
			String newStr = path.substring(
					path.lastIndexOf("/") + 1,
					path.lastIndexOf("."));					
						
	        String str=descripEditText.getText().toString();
	        avGoods.setDescription(str);
	        
	        str=unitEditText.getText().toString();
	        avGoods.setUnit(str);
	        
	        str =priceEditText.getText().toString();
	        try{     
	        	price =Float.parseFloat(str);              
        	}catch(Exception e)
        	{               
        		//log.e("stringת��int����","str="+str);
        		return;              
	        }
	        avGoods.setPrice(price);
	        
	        str=stockEditText.getText().toString();
	        try{     
	        	tmpInt =Integer.parseInt(str);              
        	}catch(Exception e)
        	{           
        		log.e("stringת��int����","str="+str);
        		return;              
	        }
	        avGoods.setStock(tmpInt);
	        
	        try {
	        	final AVFile avFile = AVFile.withAbsoluteLocalPath(newStr+".JPEG", path);
	        	try {
					avFile.save();
				} catch (AVException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
	        	avGoods.put(AntGoods.ATTR_FILE, avFile);
				
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				log.d("ʧ��","file not found!");
				//Toast.makeText(AddActivity.this, path, Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				log.d("����","file found exception!");
				//Toast.makeText(AddActivity.this, "exception", Toast.LENGTH_SHORT).show();
			}	                
	        
	        avGoods.saveInBackground(new SaveCallback() {
	            @Override
	            public void done(AVException e) {
	              if(e!=null){
	                  //�ϴ�ʧ��
	            	  log.d("ʧ��","goods upload error!");
	            	  Toast.makeText(AddActivity.this, "�����Ʒʧ��!", Toast.LENGTH_SHORT).show();
	              }else{
	                  //�ϴ��ɹ�
	            	  log.d("�ɹ�","goods upload success!");
	            	  Toast.makeText(AddActivity.this, "�����Ʒ�ɹ�!", Toast.LENGTH_SHORT).show();
	              }
	            }
	        });
		}
		
		void avsRelationQuery(){
			Thread t = new Thread(newTread);
	        t.start();
		}
		
		Runnable newTread = new Runnable() {
			 
	        @Override
	        public void run() {
	        	String sStoreInfo ="StoreInfo";
	    		AVQuery<AVObject> queryStoreInfo = new AVQuery<AVObject>(sStoreInfo);
	    		queryStoreInfo.whereEqualTo("userId", AVUser.getCurrentUser().getObjectId());
	    		queryStoreInfo.orderByAscending("updateAt");
	    		try {
		    		myStores=queryStoreInfo.find();
		    		if(myStores != null&&myStores.size()>0){
			    		AVRelation<AVObject> relation = myStores.get(0).getRelation("uptowns");	 
			    		mySections=relation.getQuery().find();	
			    	}
		    	} catch (AVException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
	    		}	
	        }
	    };
}
